<?php
namespace app\common\model;
use think\Model;
use think\Db;
use think\Loader;
use think\Validate;
use think\Request;
class Base extends Model{
    public function _initialize() {
        //parent::_initialize();
    }
    /**
     * 处理搜索条件
     * @param array $intkeys	条件为整数
     * @param array $strkeys	提交为字符串
     * @param array $randkeys	范围搜索	$randkeys = array(array('strtotime','addtime1'),array('strtotime','addtime2'))
     * @param array $likekeys	模糊搜索
     * @param array $inkeys		in搜索
     * @param array $pre		表的前缀
     */
    static public function buildSearch($intkeys=[], $strkeys=[], $randkeys=[], $likekeys=[],$inkeys=[],$pre = ''){
        $wherearr = [];
        $inputJSON = file_get_contents('php://input');
        $input = json_decode($inputJSON, TRUE);
        foreach ( $intkeys as $var ) {
            // $value = input('param.'.$var);
            $value = !empty($input[$var])||( isset($input[$var]) && $input[$var]==0)?$input[$var]:'';
            if($value !== ''){//不为空 但是可以为0
                $wherearr [] = "{$pre}{$var}='" . intval ( $value ) . "'";
            }
        }
        foreach ( $strkeys as $var ) {
            //$value = input('param.'.$var);
            $value = !empty($input[$var])||( isset($input[$var]) && $input[$var]==0)?$input[$var]:'';
            if($value != ''){
                //$wherearr [] = "{$pre}{$var}='$value'";
                //wangruifang
                $wherearr [] = "{$pre}{$var}='".self::param_filter($value)."'";
            }
        }

/*        foreach ( $randkeys as $vars ) {
            // $value1 = input('param.'.$vars['1'].'1','');
            $value1 = !empty($input[$vars['1']][1])?$input[$vars['1']][1]:'';
            //$value2 = input('param.'.$vars['1'].'2','');
            $value2 = !empty($input[$vars['1']][2])?$input[$vars['1']][2]:'';
            if($value1 !== ''){
                $wherearr [] = "{$pre}{$vars[1]}>='".$vars['0']($value1)."'";
            }
            if($value2 !== ''){
                $wherearr [] = "{$pre}{$vars[1]}<='".$vars['0']($value2)."'";
            }
        }*/

        //修改了一下 如有问题 请联系 Antely
        foreach ( $randkeys as $vars ) {
             $value1=!empty($input[$vars['1'].'1'])?$input[$vars['1'].'1']:'';
             $value2=!empty($input[$vars['1'].'2'])?$input[$vars['1'].'2']:'';
          if(!empty($value1)){
                $wherearr [] = "{$pre}{$vars['1']}>='".$vars['0']($value1)."'";
            }
            if(!empty($value2)){
                $wherearr [] = "{$pre}{$vars['1']}<='".$vars['0']($value2)."'";
            }
        }


        foreach ( $likekeys as $var ) {

            if(!empty($input[$var])){
                $value_arr = explode (' ',$input[$var]);
                if(count($value_arr) == '1' && $value_arr ['0'] !== ''){
                    //echo json_encode($value_arr[0]);exit;
                    $value = strip_search_key(self::param_filter($value_arr['0']));
                    $where = "{$pre}{$var} LIKE '%$value%'";
                }else{
                    $where = '(';
                    foreach($value_arr as $v){
                        if($v !== ''){
                            $v = strip_search_key(self::param_filter($v['0']));
                            $where .= "{$pre}{$var} LIKE '%$v%' or ";
                        }
                    }
                    $where = substr ( $where, 0, - 4 ) . ")";
                }
                $wherearr [] = $where;
            }
        }
        foreach($inkeys as $var){
            $value = !empty($input[$var]) || ( isset($input[$var]) && $input[$var]==0)?$input[$var]:'';
            if($value != ''){//不为空 但是可以为0
                if(is_array($value)){
                    $val_arr = implode ( ',', $value );
                }else{
                    $val_arr = $value;
                }
                $wherearr [] = "{$pre}{$var} in (" . $val_arr . ")";
            }
        }
        return $wherearr?' AND '.implode(' AND ',$wherearr):'';
    }

    /****
     * 排序组装
     * @param string $sort
     * @param string $order
     * @return mixed
     */
    static public function list_param($sort='addtime', $order = 'desc') {
        $inputJSON = file_get_contents('php://input');
        $input = json_decode($inputJSON, TRUE);
        $result['sort'] = !empty( $input ['sort'])?$input ['sort']:$sort;
        $sort = explode(',',$result['sort']);
        $result['order'] = !empty($input['order'])?$input['order']:$order;
        $order = explode(',',$result['order']);
        $result['order_str'] = '';
        foreach($sort as $key => $v){
            $order[$key] = !empty($order[$key])?$order[$key]:'desc';
            $result['order_str'].= $v.' '.$order[$key].',';
        }
        $result['order_str'] = rtrim($result['order_str'],',');
        $result ['page'] = !empty($input['page'])?$input['page']:1;
        $result ['rows'] = !empty($input['rows'])?$input['rows']:10;
        return $result;
    }

    /***
     * 拼接七牛域名路径(用于图片的上传写入和读取)
     * @return string
     */
    static public function qiniu_path(){
        $qiniu_config = config('qiniu');
        $project_path = $qiniu_config['DOMAIN'];
//      $project_path = $qiniu_config['DOMAIN'].'/'.$qiniu_config['PROJECT'];
        return $project_path ;
    }

    /********
     * 存储动态属性
     * @param string $info_id    //主体id  例如产品模块的就是product_id
     * @param string $model_type  //模块名id
     * @param $config_id          //动态属性id
     * @param array $config_val_id  //动态属性值id
     */
    static public function dy_attribute_storage($set_id = '',$info_id ='',$model_type='',$arr=[]){
         if(!empty($info_id) && !empty($model_type) && !empty($arr) && !empty($set_id)){
             $new_list = [];
             foreach($arr as $k =>$vv){
                 $old_val_id = Db::name('dy_attribute')->where(['web_id'=>config('web_id'),'info_id'=>$info_id,'config_id'=>$k,'set_id'=>$set_id])->column('config_val_id,config_id');
                 if(!empty($vv)){
                     foreach($vv as $key => $v){
                         if(array_key_exists($v,$old_val_id)){
                             unset($old_val_id[$v]);
                         }else{
                             $new_list['web_id'] = config('web_id');
                             $new_list['lang_id'] = config('lang_id');
                             $new_list['set_id'] = $set_id;
                             $new_list['info_id'] = $info_id;
                             $new_list['model_type'] = $model_type;
                             $new_list['config_id'] = $k;
                             $new_list['config_val_id'] = $v;
                             $ok = Db::name('dy_attribute')->insert($new_list);
                         }
                     }
//                     echo json_encode($old_val_id);exit;
                     if(!empty($old_val_id)){
                         $old_val_id = array_keys($old_val_id);
                         Db::name('dy_attribute')->where(['web_id'=>config('web_id'),'info_id'=>$info_id,'config_id'=>$k,'config_val_id'=>['in',$old_val_id]])->delete();
//                       exit;
                     }
                 }

             }
             return true;

         }else{
             return false;
         }
    }

    /***
     * 获取动态属性值
     * @param string $set_id      模型id
     * @param string $info_id     主体id
     * @param $config_id          动态属性id
     */
    static function get_dy_attribute($set_id = '',$info_id ='',$config_id =''){
       if(!empty($set_id) && !empty($info_id) && !empty($config_id)){
            $dy_attr_list = Db::name('dy_attribute')->where(['web_id'=>config('web_id'),'info_id'=>$info_id,'config_id'=>$config_id,'set_id'=>$set_id])->select();
            return !empty($dy_attr_list)?$dy_attr_list:[];
       }else{
           return false;
       }
    }

    /******
     * 拆分数组
     * @param array $arr
     * @param string $sign  拆分标识
     * @return string
     */
    static function implode_arr($arr=[],$sign=','){
        $str = '';
        if(!empty($arr) && is_array($arr)){
            foreach ($arr as $key=>$value){
                $str .= "'".$value."'{$sign}";
            }
            $str = rtrim($str,$sign);
        }
        return $str;
    }

    /*******
     * 删除分类
     * @param string $model_type
     * @param string $cate_ids
     * @return int
     */
    static function del_cate($model_type = '',$cate_ids = ''){
         if(!empty($cate_ids && !empty($model_type))){
             switch ($model_type)
             {
                 case 1:
                      $table = 'product_cate';
                      $table_relation = 'product_category_relation';
                      $module = 'product';
                 break;
                 case 2:
                     $table = 'article_cate';
                     $table_relation = 'article_cate_relation';
                     $module = 'article';
                 break;
                 case 3:
                     $table = 'link_cate';
                     $table_relation = 'link_cate_relation';
                     $module = 'link';
                 break;
                 default:
                     return -10036;
             }
             if(strpos($cate_ids,',')){
                 $where['cate_id'] = ['in',$cate_ids];
             }else{
                 $where['cate_id'] = $cate_ids;
             }
             $where['web_id'] =  config('web_id');
             $where['lang_id'] = config('lang_id');
             $list = Db::name($table_relation)->where($where)->column('id');
             if(!empty($list)){
                 return -10037;
             }else{
                 $info_name = Db::name($table)->where(['web_id'=>$where['web_id'],'lang_id'=>$where['lang_id'],'id'=>['in',$cate_ids]])->column('name');
                 $res = Db::name($table)->where(['web_id'=>$where['web_id'],'lang_id'=>$where['lang_id'],'id'=>['in',$cate_ids]])->delete();
                 if($res){
                    //liikentoo 删除关联的前端权限
                    // $top_cate = explode(',',$cate_ids,2)[0];
                    \app\power\model\FrontPower::linkDelete('cate',$cate_ids);
                     if(!empty($info_name)){
                         $info_name ='[分类标题为'. implode(',',$info_name).']';
                         $filename = date("Y-m-d");
                         $make_msg = ['username'=>config('username'),'module'=>$module,'content'=>$info_name,'type'=>4];
                         $msg = \app\common\model\Base::make_msg($make_msg);
                         if($msg!==false){
                             $log_info = ['filename'=>$filename,'module'=>$module,'info_id'=>$cate_ids,'msg'=>$msg];
                             \app\common\model\Base::write_user_log($log_info);
                         }
                     }
                     return 10003;
                 }else{
                     return -10003;
                 }
             }
         }else{
             return -18002;
         }
    }
    static  public function get_web_cache($data=[]){
        try{
            $data['is_lang'] = isset($data['is_lang'])?$data['is_lang']:true;
            $data['is_webid'] = isset($data['is_webid'])?$data['is_webid']:true;
            $data['param'] = !empty($data['param'])?$data['param']:'';
            $data['web_id'] = !empty($data['web_id'])?$data['web_id']:'';
            $data['cache_name'] = !empty($data['cache_name'])?$data['cache_name']:'';
            if(!empty($data['cache_name'])){
                $path_cache_name = $data['cache_name'];
                if(isset($data['is_lang']) && $data['is_lang'] == true){
                    $lang_id = config('lang_id');
                    $path_cache_name = $path_cache_name.'_'.$lang_id;
                }
                if(!empty($data['param'])){
                    $path_cache_name = $path_cache_name.'_'.$data['param'];
                }
                if(cache($path_cache_name ,'',get_cache_path($data['is_webid'],$data['web_id'])) === false){
                    if(function_exists($data['cache_name'].'_cache')){
                        call_user_func($data['cache_name'].'_cache',$data['web_id']);
                    }else{
                        return [];
                    }
                }
                //echo json_encode($path_cache_name);exit;
                return cache($path_cache_name ,'',get_cache_path($data['is_webid'],$data['web_id']));
            }

        }catch(\Exception $e){
            return [];
        }
    }

    /**
     * 获取终端类型
     * @param  String $domain 二级域名
     * @return [type]         [description]
     */
    public static function get_client_id(String $domain){
        $prefix = explode('.',$domain)[0];
        switch ($prefix) {
            case 'wx' :
                return 2;
            case 'app' :
                return 3;
            case 'h5' :
                return 4;
            case 'mp' :
                return 5;
            default :
                return isMobile()?(isWeixin()?2:4):1;
        }
    }

    /**********
     * 检测微信公众号功能是否已授权
     * $num  当前功能的键值
     * $power_list 所授权的列表键值
     */
    static public function check_weixin_power($num='',$power_list=''){
        if(!empty($num) && !empty($power_list)){
            $power_list = explode(',',$power_list);
            if(in_array($num,$power_list)){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }

    }

    /***
     * 检测凭证是否过期及刷新凭证
     * @param string $web_id
     * @return bool|mixed
     */
   static public function check_authorizer_access_token($web_id = ''){
        if(!empty($web_id)){
            Loader::import('thirdparty.WechatTool','','.class.php');
            $tool_obj = new \WechatTool();
            $wx_info = Db::name('wechat_config')->where(['web_id'=>$web_id])->field('authorizer_access_token,expires_in,authorizer_refresh_token,appid,updatetime')->find();
            if(request()->time()>$wx_info['updatetime']+$wx_info['expires_in']){
                $component_access_token = controller('wechat/Thirdparty')->get_component_access_token(config('THIRD_PARTY.THIRD_PARTY_APPID'));
//                    echo $aaaa;exit;
                $refresh = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=".$component_access_token;
                $post_arr = [
                    'component_appid'=>config('THIRD_PARTY.THIRD_PARTY_APPID'),
                    'authorizer_appid'=>$wx_info['appid'],
                    'authorizer_refresh_token'=>$wx_info['authorizer_refresh_token']
                ];
                $new_authorizer_access_token = $tool_obj->doCurlPostRequest($refresh,json_encode($post_arr));
                $new_authorizer_access_token = json_decode($new_authorizer_access_token,true);

//                    echo 111;exit;

                if(!empty($new_authorizer_access_token)){
                    $new_authorizer_access_token['updatetime'] = request()->time();
                    $wx_info = Db::name('wechat_config')->where(['web_id'=>$web_id,'appid'=>$wx_info['appid']])->update($new_authorizer_access_token);
//                        echo 'success';exit;
                }
                return $new_authorizer_access_token['authorizer_access_token'];
            }
            return $wx_info['authorizer_access_token'];
        }else{
            return false;
        }
    }
    /**
     * @param string $data
     * @return string
     * wangruifang 0425
     */
    public static function param_filter($data=''){
        if(is_string($data) && !empty($data)){
            // 判断magic_quotes_gpc是否为打开
            if (!get_magic_quotes_gpc()){
                $data = addslashes($data); // 进行magic_quotes_gpc没有打开的情况对提交数据的过滤
            }
            //$data = strtr($data,array('_'=>'＼_','%'=>'＼%')); //把 '_' 和 ' % ' 过滤掉
            $data = strtr($data,array('%'=>'＼%')); //把 '_' 和 ' % ' 过滤掉
            $data = nl2br($data); // 回车转换
            $data= htmlspecialchars($data); // html标记转换
        }
        return $data;
    }

    /*******
     * 浏览数+1
     * @param string $module  模块名称
     * @param string $id      主体id
     * @return bool
     */
    public static function set_num_add($module='',$id=''){
        if(!empty($module) && !empty($id)){
            $modules = ['article','link','product','album'];
            if(in_array($module,$modules)){
                $cache = cache($module.'_click_num','',get_cache_path());
                if(!empty($cache) && !empty($cache[$id])){
                    $cache[$id] +=1;
                }else{
                    $cache[$id] = 1;
                }
                cache( $module.'_click_num', $cache,get_cache_path());
                return $cache[$id];
            }

        }else{
            return 0;
        }
    }

    /******
     * @param $filename 日志名称（以当天日期为名）
     * @param string $module 操作的模块
     *  * @param string $info_id 操作的主体id
     * @param $msg 日志具体信息
     */
    public static function write_user_log($arr = []){
        if(!empty($arr['filename']) && !empty($arr['module']) && !empty($arr['info_id']) && !empty($arr['msg'])){

            $res = [];
            $res['module'] = $arr['module'];
            $res['info_id'] = $arr['info_id'];
            $res['msg'] = $arr['msg'];
            $res['logtime'] = date("Y-m-d H:i:s",time());

            $filename = ROOT_PATH.'runtime/log/'.config('web_id').'/'.$arr['filename'].'.txt';

            if(!is_dir(dirname($filename))){
                mkdir(dirname($filename));
            }
            //如果是新建的日志文件，去掉内容中的第一个字符逗号
            if(file_exists($filename) && abs(filesize($filename))>0){
                $content = ",".json_encode($res);
            }else{
                $content = json_encode($res);
            }
            //往日志文件内容后面追加日志内容
            file_put_contents($filename, $content, FILE_APPEND);
        }else{
            return false;
        }

    }


    /*******
     *读取操作日志
     * @param $filename
     * @return bool|mixed
     */
    public static function read_user_log($filename){
        $filename = ROOT_PATH.'runtime/log/'.config('web_id').'/'.$filename.'.txt';
        if(file_exists($filename)){
            $content = file_get_contents($filename);
            $json = json_decode('['.$content.']',true);
        }else{
            $json = false;
        }
        return $json;
    }

    /******
     * @param username 日志名称
     * @param module 模块名称
     * @param content 信息主体内容   格式：[标题为xxx的内容]
     * @param int type 表示动作增删改 1: 添加 ；2 ：编辑 ； 3：删除到回收站  4：彻底删除 5：还原
     * @param $custom 自定义内容 Paulbi 2017.6.15加
     * @return bool|string
     */
    public static function make_msg($arr = [],$custom=''){
        if(!empty($arr['username']) && !empty($arr['module']) && !empty($arr['content']) && !empty($arr['type'])){
            switch ($arr['type']) {

                case 1:
                    $action = '添加了';
                    break;
                case 2:
                    $action = '编辑了';
                    break;
                case 3:
                    $action = '删除了';
                    $recycle = '到回收站';
                    break;
                case 4:
                    $action = '彻底删除了';
                    break;
                case 5:
                    $action = '还原了';
                    break;
                default:
                    return false;
            }
            if(empty($recycle)) $recycle = '';
            if(!empty($custom)){
                $msg = $custom.'(操作人：'.$arr['username'].',操作时间：'.date('Y-m-d H:i:s',request()->time()).',操作模块：'.$arr['module'].',操作：'.$action.')';
            }else{
                $msg = $arr['username'] . '在'.date('Y-m-d H:i:s',request()->time()).$action.$arr['module'].'模块里面'.$arr['content'].'的内容'.$recycle;
            }
            $msg .=',ip:'.request()->ip();
            return $msg;
        }else{
            return false;
        }
    }

    /**
     * @param array $where
     * @param string $field
     * @param string $table_name
     * @return array|false|mixed|\PDOStatement|string|Model
     * 查询指定表的信息
     * wangruifang
     */
    public static function get_table_info($where=[],$field='*',$table_name ='Templet'){
        if(!empty($where)){
            if(('*' == $field) || (strpos($field,','))){
                $one = Db::name($table_name)->where($where)->field($field)->find();
            }else{
                $one = Db::name($table_name)->where($where)->value($field);
            }
        }
        return !empty($one)?$one:null;
    }

    /**
     * @param $url 提交的url
     * @param $request 提交数据
     * @param int $timeout
     * @return bool|mixed
     * wangruifang
     */
    static public function curl_post($url, $request, $timeout = 5) {
        if($url == "" || $request == "" || $timeout <= 0){
            return false;
        }
        $con = curl_init((string)$url);
        curl_setopt($con, CURLOPT_URL, $url);
        curl_setopt($con, CURLOPT_HEADER, false);
        curl_setopt($con, CURLOPT_POSTFIELDS, json_encode($request));
        curl_setopt($con, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($con, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($con, CURLOPT_POST, true);
        curl_setopt($con, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($con, CURLOPT_TIMEOUT, (int)$timeout);
        $output =  curl_exec($con);
        curl_close($con);
        return  json_decode($output);
    }
    /**
     * 发送HTTP请求方法，目前只支持CURL发送请求
     * @param  string $url    请求URL
     * @param  array  $params 请求参数
     * @param  string $method 请求方法GET/POST
     * @return array  $data   响应数据
     */
static public function api_http($url, $params, $method = 'POST', $header = array(), $multi = false){

        try{
            $opts = array(
                CURLOPT_TIMEOUT        => 30,
                CURLOPT_RETURNTRANSFER => 1,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false,
                CURLOPT_HTTPHEADER     => $header,
                CURLOPT_COOKIESESSION     => false,
//                HTTP_USER_AGENT => true
            );

            /* 根据请求类型设置特定参数 */
            switch(strtoupper($method)){
                case 'GET':
                    $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                    break;
                case 'POST':
                    //判断是否传输文件
                    //$params = $multi ? $params : http_build_query($params);
                    $opts[CURLOPT_URL] = $url;
                    $opts[CURLOPT_POST] = 1;
                    $opts[CURLOPT_POSTFIELDS] = $params;
                    break;
                default:
                    throw new Exception('不支持的请求方式！');
            }

            /* 初始化并执行curl请求 */
            $ch = curl_init();
            curl_setopt_array($ch, $opts);

            //curl_setopt($ch, CURLOPT_HEADER, true);
            curl_setopt ($ch, CURLOPT_COOKIE ,"value:".cookie('test'));
            $data  = curl_exec($ch);
            $error = curl_error($ch);
            curl_close($ch);
            if($error) throw new Exception('请求发生错误：' . $error);
            return  $data;
        }catch (\Exception $e){
            throw $e;
        }
    }

    /**
     * @param $array
     * @return array
     * 对象转为数组
     * wangruifang
     */
    static public function object_array($array) {
        if(is_object($array)) {
            $array = (array)$array;
        } if(is_array($array)) {
            foreach($array as $key=>$value) {
                $array[$key] = self::object_array($value);
            }
        }
        return $array;
    }


    /********
     * 根据模型id获取系统字段
     * @param $set_id
     * @return bool
     */
    static public function get_system_fields($set_id){
         if(!empty($set_id)){
             ext_sys_fields_cache();
             $ext_sys_fields = take_cache('ext_sys_fields',false);
             $fields = '*';
//             if($set_id == 'fieldSet_ee420b51'){
//                 echo json_encode($ext_sys_fields[$set_id]);die;
//             }
             if(!empty($ext_sys_fields[$set_id]['system_fields'])){
                 $fields ="id,set_id,web_id,lang_id,type_id,uid,".$ext_sys_fields[$set_id]['system_fields'];
             }
             return $fields;
         }else{
             return false;
         }
    }

    /******
     * 检测自定义字段必填字段是否已传
     * @param array $data 前端传过来的参数
     * @return bool|int
     */
    static public function check_extend_fields($data = []){
        if(!empty($data['set_id'])){
            //获取扩展字段
            $ex_field = take_cache('extend_fields',false);
//            echo json_encode($ex_field);exit;
            $ex_fields_check = [];
            if(!empty($ex_field) && is_array($ex_field)){
                foreach($ex_field as $v){
                    if($v['set_id'] == $data['set_id'] && $v['is_require']==1){
                        $ex_fields_check[] = [$v['field'],'require',$v['name'].'字段必填'];
                    }
                }
            }
//            echo json_encode($ex_fields_check);exit;
            if(!empty($ex_fields_check)){
//                echo json_encode($ex_fields_check);exit;
                $validate = new Validate();

                $check = $validate->check($data,$ex_fields_check);
                if($check !==true){
                    $error_msg = $validate->getError();
//                    $info['msg'] = $error_msg;
//                    $info['status'] =0;
                    return $error_msg;
                }
            }
//            $info['msg'] = '';
//            $info['status'] =1;
            return true;

        }else{
            return  -10033;
        }
    }

    /**
     * @param string $field_set_id
     * @return bool
     * 通过模型获取对应的语言版本id
     * wangruifang
     * 参数或者模型不存在,则返回false,反之返回对应的语言版本id
     */
    static  public function get_field_set_lang($field_set_id=''){
        if(!empty($field_set_id)){
            $field_set = take_cache('fields_set',false);
            if(!empty($field_set[$field_set_id])){
                return !empty($field_set[$field_set_id]['lang_id'])?$field_set[$field_set_id]['lang_id']:false;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    /**
     * @param string $model_type
     * @return int
     * 创建key_id 默认10是组装
     */
    static public function creat_key_id($model_type='10'){
        Loader::import('Sequence.Sequence');
//        $sequence = new \Sequence(1,!empty($model_type)?$model_type:10);
        $sequence = new \Sequence();
        return $sequence->nextId();
    }
    static public function get_domain_set($prefix='',$is_http=0){
        //域名配置还没稳定,先开启缓存更新
        domain_set_cache();
        $domain = take_cache('domain_set',false,false);
        if(DEV==1){
            $domain['pms_domain']= $domain['dev_pms_domain'];
            $domain['curl_api']= $domain['dev_curl_api'];
            $domain['mall_domain']= $domain['dev_mall_domain'];
            $domain['ucenter_url']= $domain['dev_ucenter_url'];
        }
        if(!empty($domain) && !empty($prefix)){
            $domain =  !empty($domain[$prefix])?$domain[$prefix]:'';
            if(!empty($domain) && $is_http){
                $domain = preg_http($domain);
            }
            return $domain;
        }
        return $domain;
    }
    static public function check_domain($url,$data){
        $web_info = cache('getwebid_'.$data['domain'],'',get_cache_path());
        if(empty($web_info) || (!empty($web_info) && $web_info['expire'] < request()->time())) {
            $output = \app\common\model\Base::curl_post($url, $data);
            $output = \app\common\model\Base::object_array($output);
            if (!empty($output) && $output['code'] > 0) {
                $web_info['web_id'] = $output['data']['web_id'];
                $web_info['site_type'] = $output['data']['site_type'];
                $web_info['domain'] = $data['domain'];
                $web_info['expire'] = request()->time() + 6000;
                cache('getwebid_'.$data['domain'],$web_info,get_cache_path());
                return $web_info;
            } else {
                return false;
            }
        }else{
            return $web_info;
        }
    }
    static public function get_web_domain($web_id){
        $web_domain = cache('domain_'.$web_id,'',get_cache_path());
        if(empty($web_domain) || (!empty($web_domain) && $web_domain['expire'] < request()->time())){
            $mall_domain = self::get_domain_set('mall_domain',1);
            $output = \app\common\model\Base::curl_post($mall_domain.'/api/domain/get_web_domain',['web_id'=>$web_id]);
            $output = \app\common\model\Base::object_array($output);
            if(!empty($output) && $output['code'] > 0 ){
                $domaim = $output['data']['domain'];
                $arr['expire'] = request()->time() + 6000;
                $arr['domain'] = $output['data']['domain'];
                cache('domain_'.$web_id,$arr,get_cache_path());
                unset($arr);
                return $output['data']['domain'];
            }else{
                return false;
            }
        }else{
            return $web_domain['domain'];
        }
    }

    /**
     * @param $domain
     * @param get_web_domain $
     * 根据端口处理域名前缀
     */
    static public function domain_preg($domain,$client_id='1'){
        $client = ['wms','h5','wx','app','mp'];
        switch ($client_id) {
            case 2 :
               $type_name = 'app,h5,mp,wms';
                break;
            case 3 :
                $type_name = 'wx,h5,mp,wms';
                break;
            case 4 :
                $type_name = 'app,wx,mp,wms';
                break;
            case 5 :
                $type_name = 'app,h5,wx,wms';
                break;
            case 0 :
                $type_name = 'app,h5,wx,mp';
                break;
            default :
                $type_name = 'wx,app,h5,mp,wms';
                break;
        }
        $type_arr = explode(',',$type_name);
        $domain_exp = explode('.',$domain);
        $array_diff = array_values(array_diff($client,$type_arr));
        $replace = !empty($array_diff)?$array_diff[0].'.':'';
        if(in_array($domain_exp[0],$type_arr)){
            $domain = str_replace($domain_exp[0].'.',$replace,$domain);
        }elseif($domain_exp[0].'.' != $replace && ($domain_exp[0] != 'www')){
            $domain = $replace.$domain;
        }
        return $domain;
    }
    static public function keywords_cutout($keywords){
        $key_word = $keywords;
        if(false !== strpos($keywords,'T')){
            $key_word = str_replace('T','',$keywords);
        }elseif(false !== strpos($keywords,'t')){
            $key_word = str_replace('t','',$keywords);
        }
        $key_id  = (int)$key_word;
        return $key_id;
    }

    /******
     * @param $arr
     * 检测会员权限
     * arr['is_front'] 前端登录
     * arr['web_id'] 站点id
     * arr['set_id'] 模型id
     * arr['cate_id'] 分类id
     */
    static public function check_member_power($arr){

    }
    static public function get_userinfo($list=[]){
        $user_infos = [];
        if(!empty($list)){
            $all_uid = array_column($list,'uid');
            if(!empty($all_uid)){
                $all_uid = array_unique($all_uid);
                $all_uid = array_diff($all_uid,[0]);
                if(!empty($all_uid)){
                    $user_infos = Db::name('Member')->where(['uid'=>['in',$all_uid]])->field('uid,username')->select();
                    if(!empty($user_infos)){
                        $user_infos = array_column($user_infos,'username','uid');
                    }
                }
            }
            unset($all_uid);
        }
        unset($list);
        return $user_infos;
    }

    /****
     * 检测模型下的分类
     */
    static public function check_list_power($data=[]){
         $res['status'] = 1;
         if(!empty($data['token'])){
             $web = cache($data['token'],'',get_cache_path(false));
             if(!empty($web)){
                 if($web['identify']==0){      //平台登录
                       $res['data'] = $data;
                 }elseif(in_array($web['identify'],[1,2,3,4])){      //类型标识（1平台员工 2用户 3门店 4门店员工）
                      $front_power = config('front_power');
                     if(!empty($front_power['publish']['set'][$data['set_id']])){
                         if(!empty($data['cate_id'])){
                             $cate_ids = explode(',',$data['cate_id']);
                             $request = Request::instance();
                             $sub_name = $request->module();
                             switch($sub_name){
                                 case 'product':
                                     $cate_list = Db::name('product_cate')->where(['set_id'=>$data['set_id']])->field('id,pid')->select();
                                     break;
                                 case 'article':
                                     $cate_list = Db::name('article_cate')->where(['set_id'=>$data['set_id']])->field('id,pid')->select();
                                     break;
                                 case 'album':
                                     $cate_list = Db::name('album_category')->where(['set_id'=>$data['set_id']])->field('id,pid')->select();
                                     break;
                                 default :
                                     $res['status'] = 0;
                                     $res['code'] = -10040;
                                     return $res;
                             }
                             foreach($cate_ids as $v){
                                 $fid = getTreeParent($cate_list,$v);
                                 if(!empty($fid)){
                                     $fid = array_reverse(explode(',',ltrim($fid,',')));
                                     if(empty($front_power['publish']['set'][$data['set_id']])) return ['status'=>0,'code'=>-10040];
                                     if(!in_array($fid[0],$front_power['publish']['set'][$data['set_id']])){
                                         $res['status'] = 0;
                                         $res['code'] = -10040;
                                         return $res;
                                     }
                                 }
                             }
                         }else{  //没有传分类id
                             $data['cate_id'] = implode(',',$front_power['publish']['set'][$data['set_id']]);
                         }
                     }
                     $res['data'] = $data;
                 }else{
                     $res['status'] = 0;
                     $res['code'] = -11237;
                 }
             }else{
                 $res['status'] = 0;
                 $res['code'] = -11406;
             }
         }else{
             $res['status'] = 0;
             $res['code'] = -13001;
         }
        return $res;
    }

}





